<?php if (!defined('BASEPATH'))exit('No direct script access allowed');
/**
 * 自动化脚本
 */
class Automatic extends CI_Controller {

    function __construct()
    {
        parent::__construct();
        $this->load->model('plat_model');
        $this->load->model('lend_list_model');
        $this->load->model('sort_record_model');
        $this->load->model('reload_log_model');
        $this->load->model('reload_rule_model');
        $this->load->model('subtasks_model');
        $this->load->model('task_model');
        $this->load->model('../../Back/app/models/statistics_model');
    }
    //平台排序
    function plat_sort(){
        //1.读取规则库的所有股则
        $rules = $this->reload_rule_model->get_list(array('is_valid'=>1));
        //2.遍历规则，读出plat_id集合  计算plat_id浏览量 点击量 满足条件 给palt 增肌score值
        $rule_name_arr = array();
        $all_plats =  $this->lend_list_model->get_all_list(array('is_mobile'=>1,'status'=>1));
        $now_time = time();

        $temp_plat_score_arr = array();
        foreach ($all_plats as $one){
            $temp_plat_score_arr[$one['id']] = $one['sort'];
        }
        foreach ($rules as $one_rule){
            //判断规则是否已经过期，过期就更新掉，不走下面的逻辑
            if(  $one_rule['valid_hour']>0 && ($one_rule['add_time'] + $one_rule['valid_hour']*3600 < $now_time) ){
                $update_data = array('is_valid'=>0);
                $where = array('id'=>$one_rule['id']);
                $this->reload_rule_model->update($update_data,$where);
                continue;
            }

            $rule_name_arr[] = $one_rule['rule_name'];
            $plat_id = $one_rule['plat_id'];
            $type = $one_rule['type'];
            $time_type = $one_rule['time_type'];
            $time_value = $one_rule['time_value'];
            $num = $one_rule['num'];
            $time_effect = explode('--',$one_rule['time_effect']);
            $rule_start_time = strtotime(date('Y-m-d ',$now_time).$time_effect[0]);
            $rule_end_time   = strtotime(date('Y-m-d ',$now_time).$time_effect[1]);
            if($now_time < $rule_start_time || $now_time > $rule_end_time ){
                //不符合规则的作用时间
                continue;
            }
            if(empty($plat_id)){
                //计算所有平台的浏览量和点击量
                $plats = $all_plats;
            }else{
                $plat_arr = explode(',',$plat_id);
                $plats = $this->lend_list_model->get_all_list_in($plat_arr);
            }
            foreach ($plats as $one_plat){
                if($type==0){
                    //直接加分
                    $temp_plat_score_arr[$one_plat['id']] = $temp_plat_score_arr[$one_plat['id']] + $one_rule['score'];
                    continue;
                }
                $where['type_val'] = $one_plat['id'];
                if($time_type == 0){

                } elseif($time_type == 1){
                    //全天
                    $where['request_time >='] = strtotime(date('Y-m-d',$now_time));
                }elseif($time_type == 2){
                    //多少时间段内
                    $a = $now_time - $time_value*60;;
                    $where['request_time >='] = $now_time - $time_value*60;
                }elseif($time_type == 3){
                    //某个时间点内

                    $time_value_arr = explode('--',$time_value);
                    $start_time = strtotime(date('Y-m-d ',$now_time).$time_value_arr[0]);
                    $end_time   = strtotime(date('Y-m-d ',$now_time).$time_value_arr[1]);
                    $where['request_time >='] = (int)$start_time;
                    $where['request_time <='] = (int)$end_time;
                }
                $temp_num = 0;
                if($type==1){
                    $where['type'] = 1;

                }elseif($type==2){
                    $where['type'] = 2;
                }
                $temp_num = $this->reload_log_model->get_count($where);
                if($one_rule['rule_direct']==1 && $temp_num >= $num){
                    //正向规则
                    $temp_plat_score_arr[$one_plat['id']] = $temp_plat_score_arr[$one_plat['id']] + $one_rule['score'];
                }elseif($one_rule['rule_direct']==0 && $temp_num < $num){
                    //反向规则
                    $temp_plat_score_arr[$one_plat['id']] = $temp_plat_score_arr[$one_plat['id']] + $one_rule['score'];
                }
                //如果type==0，直接去加分，time_type没有不需要时间

            }
        }
        //3.记录当前排序 用的是什么规则 并且排行的序列是什么
        $rule_name_str = implode(',',$rule_name_arr);
        $all_plats =  $this->lend_list_model->get_all_list(array('is_mobile'=>1,'status'=>1));
        $id_arr = array();
        $num = count($temp_plat_score_arr);
        $sort_arr = arsort($temp_plat_score_arr);
        $location = 0;
        foreach ($temp_plat_score_arr as $key_id=>$val){
            $update_data = array('sort'=>$num - $location);
            $this->lend_list_model->update_plat($update_data,$key_id);
            $location++;
        }

        $id_str = implode(',',$id_arr);
        //4.根据现在的排序，重置积分
        $data = array('lid_sort'=>$id_str,'rule_list'=>$rule_name_str,'add_time'=>date('Y-m-d H:i:s',time()));
        return $this->sort_record_model->insert_sort_record($data);
    }

    //任务操作脚本
    function task_handle(){
        //1.操作任务
        $web_config = $this->task_model->website_config();
        $time_subtask_not_hadle =  $web_config['task_fail_period'] * 3600;;//任务1小时内不操作，回退
        $now_time = time();
        $where_1 = array(
            'is_end'=>0,
            'is_post'=>0,
        );
        $subtaks_list = $this->subtasks_model->subtask_list($where_1);

        foreach ($subtaks_list as $one_subtask){
            if($one_subtask['add_time'] + $time_subtask_not_hadle < $now_time){
                $update_arr = array('is_end'=>2,'status'=>3);
                $where_2 = array('sid'=>$one_subtask['sid']);
                $this->subtasks_model->update_subtask($update_arr,$where_2);
            }
        }

        //2.操作任务申诉
        $time_subtask_not_hadle = $web_config['task_judgefail_period'] * 3600;;//6小时内不操作申诉，回退
        $now_time = time();
        $where_1 = array( 'is_end'=>0,'status'=>2);
        $subtaks_list = $this->subtasks_model->subtask_list($where_1);
        foreach ($subtaks_list as $one_subtask){
            $where_2 = array('sid'=>$one_subtask['sid']);
            if( !$this->subtasks_model->complaint_list($where_2)){
                //没有申诉记录
                $update_arr = array('is_end'=>2);
                $where_3 = array('sid'=>$one_subtask['sid']);
                $this->subtasks_model->update_subtask($update_arr,$where_3);
            }
        }
        //3.处理未处理的申诉
        $where_1 = array( 'status'=>0);
        $complaint_list = $this->subtasks_model->complaint_list($where_1);

        $complaint_time = $web_config['task_promulgator_period'] * 3600;
        $now_time = time();
        //list只会有一条数据
        foreach ($complaint_list as $one_complaint){
            if($one_complaint['add_time'] + $complaint_time > $now_time){
                //1.tan_complaint 的status设置为2
                $update_arr = array('status'=>2);
                $where_2 = array('cid'=>$one_complaint['cid']);
                $this->subtasks_model->update_complaint($update_arr,$where_2);
                //2.subtask 设置is_end=1 status=1 并且发放佣金
                $update_arr = array('is_end'=>1,'status'=>1);
                $where_2 = array('sid'=>$one_complaint['sid']);
                $this->subtasks_model->update_subtask($update_arr,$where_2);
                //3.发放佣金
                $this->subtasks_model->give_money($one_complaint['sid']);
            }
        }
        //4.处理未处理的客服
        $where_1 = array( 'status'=>1,'is_kefu'=>0);
        $complaint_list = $this->subtasks_model->complaint_list($where_1);
        $kefu_time = $web_config['task_receiver_period'] * 3600;
        $now_time = time();
        //list只会有一条数据
        foreach ($complaint_list as $one_complaint){
            if($one_complaint['add_time'] + $kefu_time < $now_time){
                //1.tan_complaint 的status设置为5，申诉失败
                $update_arr = array('status'=>5);
                $where_2 = array('cid'=>$one_complaint['cid']);
                $this->subtasks_model->update_complaint($update_arr,$where_2);
                //2.subtask 设置is_end=2 任务失败
                $update_arr = array('is_end'=>2);
                $where_2 = array('sid'=>$one_complaint['sid']);
                $this->subtasks_model->update_subtask($update_arr,$where_2);
            }
        }
    }

    //平台来源注册人数统计（凌晨12:05分统计，统计昨天的数据）
    function platreg(){
        //统计昨天总共注册人数，获取最近的一条设置，（300-200）* （100-10）*1.0/100+77
        //如果记录是当天的，就更新，如果没有插入数据（百分比从配置里面获取）
        $time_00 = strtotime(date('Y-m-d',time()));
        $date_yes = date("Y-m-d",strtotime("-1 day"));
        //1.获取所有来源
        $dictionary_list = $this->db->query("select * from tan_dictionary where type=1 and value>=100")->result_array();
        foreach ($dictionary_list as $key=>$one_dic){
            $log_sql = "select * from tan_platreg_log where dic_id={$one_dic['id']} and log_time='{$date_yes}'";
            $one_log = $this->db->query("{$log_sql}")->row_array();
            $list = $this->statistics_model->get_platreg_day($one_dic['id'],$date_yes);
            $per_num = $list['percent_num'];
            $real_num = $list['real_num'];
            $percent = $list['percent'];
            if(empty($one_log)){
                //什么记录都没有，统计昨天人数，加一条记录
                $sql = "insert into tan_platreg_log (dic_id,percent,real_num,per_num,end_num,log_time) values({$one_dic['id']},$percent,$real_num,$per_num,$per_num,'{$date_yes}')";
                $this->db->query("{$sql}");
            }else{
                //跟最近一条数据进行比较，直接公式计算
                $per_num = floor( ($real_num - $one_log['real_num']) * (100 - $one_log['percent'])*1.0/100 ) + $one_log['per_num'];
                $sql = "update tan_platreg_log set dic_id={$one_dic['id']},percent={$percent},real_num={$real_num},per_num={$per_num},end_num={$per_num},log_time='{$date_yes}' where id={$one_log['id']}";
                $this->db->query("{$sql}");
            }
        }
    }
     //凌晨12:05每天的贷款平台统计记录表www.tan66.com/automatic/day_lend_log.html
    function day_lend_log(){
        $date_yes = date("Y-m-d",time());
        //1.获取所有来源
        $lend_list = $this->db->query("select id from tan_lend_list WHERE status = 1 and is_mobile=1 order by id desc")->result_array();
        $id_arr = array();
        foreach ($lend_list as $one){
            $id_arr[] = $one['id'];
        } 
        $ids = empty($id_arr)?0:implode(',',$id_arr);
        $log_existes = $this->db->query("select * from tan_lend_day_log where time_date='{$date_yes}'")->row_array();
        if($log_existes){
            $sql = "update tan_lend_day_log set lend_id='$ids'";
            $this->db->query("{$sql}");
        }else{
            $sql = "insert into tan_lend_day_log (lend_id,time_date) values('$ids','$date_yes')";
            $this->db->query("{$sql}");
        }
      
    }
}
